<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row :gutter="24">
          <a-col :span="8">
            <a-row>
              <a-col :span="24">
                <a-form-model-item label="客户编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="code">
                  <a-input v-model="model.code" placeholder="系统自动生成" disabled></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item label="客户名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="name">
                  <a-input v-model="model.name" placeholder="请输入客户名称"></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item label="其他名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="simpleName">
                  <a-input v-model="model.simpleName" placeholder="请输入其他名称"></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item label="国家" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="countryId">
                  <j-dict-select-tag
                    type="list"
                    v-model="model.countryId"
                    @change="handleChange"
                    dictCode="erp_country,country_name,country_id"
                    placeholder="请选择国家"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item label="业务员" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="salesman">
                  <a-input v-model="model.salesmanName" @click="handleClick"></a-input>
                  <select-hr-employee-modal ref="hr" @Ok="handleHr"></select-hr-employee-modal>
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item label="客户类别" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="type">
                  <j-dict-select-tag
                    type="list"
                    v-model="model.type"
                    dictCode="customer_category"
                    placeholder="请选择客户类别"
                  />
                </a-form-model-item>
              </a-col>
<!--              <a-col :span="24">-->
<!--                <a-form-model-item label="客户类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="category">-->
<!--                  <j-dict-select-tag-->
<!--                    type="list"-->
<!--                    v-model="model.category"-->
<!--                    dictCode="erp_customer_category,name,id"-->
<!--                    placeholder="请选择客户类型"-->
<!--                  />-->
<!--                </a-form-model-item>-->
<!--              </a-col>-->
              <a-col :span="24">
                <a-form-model-item label="品牌" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="brand">
                  <a-input v-model="model.brand" placeholder="请输入品牌"></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item label="首次下单日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="deDate">
                  <j-date placeholder="请选择首次下单日期" v-model="model.deDate" style="width: 100%" />
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item label="联系人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="contact">
                  <a-input v-model="model.contact" placeholder="请输入联系人"></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item label="联系电话" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="telephone">
                  <a-input v-model="model.telephone" placeholder="请输入联系电话"></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item label="地址" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="address">
                  <a-input v-model="model.address" placeholder="请输入地址"></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item label="销售区域" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="salesArea">
                  <a-input v-model="model.salesArea" placeholder="请输入销售区域"></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item label="税号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="tin">
                  <a-input v-model="model.tin" placeholder="请输入税号"></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item label="开户行" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="bank">
                  <a-input v-model="model.bank" placeholder="请输入开户行"></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item label="账号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="account">
                  <a-input v-model="model.account" placeholder="请输入账号"></a-input>
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-col>
          <a-col :span="16">
            <a-tabs v-model="activeKey" @change="handleChangeTabs">
              <a-tab-pane tab="销售产品" :key="refKeys[0]" :forceRender="true">
                <a-row :gutter="20" style="margin-bottom: 10px;">
                  <a-col :span="20">
                    <a-button @click="addProducts" icon="plus">新增</a-button>
                  </a-col>
                </a-row>
                <j-vxe-table
                  keep-source
                  :ref="refKeys[0]"
                  :loading="tslSellProductsDetailTable.loading"
                  :columns="updatedColumns"
                  :dataSource="tslSellProductsDetailTable.dataSource"
                  :maxHeight="300"
                  :disabled="formDisabled"
                  :rowNumber="true"
                  :rowSelection="true"
                  :toolbar="true"
                  :toolbarConfig="{ slot: ['prefix', 'suffix'], btn: ['remove', 'clearSelection'] }"
                >
                  <template #action="props">
                    <a-popconfirm title="确定删除吗？" @confirm="handleDeleteRow(props)">
                      <a>删除</a>
                    </a-popconfirm>
                  </template>
                </j-vxe-table>
              </a-tab-pane>
            </a-tabs>
            <select-material-modal ref="selectModal" @orderOk="sellProductsOk" />
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
  </a-spin>
</template>

<script>
import { httpAction, getAction, postAction } from '@/api/manage'
import { getRefPromise } from '@comp/jeecg/JVxeTable/utils/vxeUtils'
import { JVXETypes } from '@comp/jeecg/JVxeTable'
import ErpCategoryGoodsListModal from '@comp/base/modal/ErpCategoryGoodsListModal.vue'
import SelectMaterialModal from '@views/erp/base/modules/SelectMaterialModal.vue'
import SelectHrEmployeeModal from '@comp/base/modal/SelectHrEmployeeModal.vue'

export default {
  name: 'ErpCustomerForm',
  components: { SelectHrEmployeeModal, SelectMaterialModal, ErpCategoryGoodsListModal },
  props: {
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false
    }
  },
  data() {
    return {
      modalWidth: 1200,
      refKeys: ['tslSellProductsDetail'],
      activeKey: 'tslSellProductsDetail',
      tslSellProductsDetailTable: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: '物料编码',
            key: 'code',
            type: JVXETypes.normal,
            width: '150px'
          },
          {
            title: '物料名称',
            key: 'name',
            type: JVXETypes.normal,
            width: '300px'
          },
          {
            title: '规格型号',
            key: 'noneSpec',
            type: JVXETypes.normal,
            width: '100px'
          },
          {
            title: '主单位',
            key: 'meUnit',
            type: JVXETypes.normal,
            width: '100px'
          },

          {
            title: '辅单位',
            key: 'auUnit',
            type: JVXETypes.normal,
            width: '100px'
          },
          {
            title: '换算率',
            key: 'coRate',
            type: JVXETypes.normal,
            width: '150px'
          },
          {
            title: '操作',
            key: 'actions',
            width: '150px',
            align: 'center',
            fixed: 'right',
            type: JVXETypes.slot,
            slotName: 'action'
            /*scopedSlots: {
              customRender: (text, record) => {
                return (
                  <a-button onClick={() => this.handleDeleteRow(record)}>
                    删除
                  </a-button>
                )
              }
            }*/
          }
        ]
      },
      model: {
        salesmanName:'',
        status: 1,
        salesman:'',
        tslSellProductsDetail: [
          {
            id: '',
            code: '',
            name: '',
            noneSpec: '',
            meUnit: '',
            auUnit: '',
            coRate: ''
          }
        ]
      },
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      textareaLabelCol: {
        xs: { span: 12 },
        sm: { span: 2 }
      },
      textareaWrapperCol: {
        xs: { span: 40 },
        sm: { span: 21 }
      },
      confirmLoading: false,
      validatorRules: {
        name: [{ required: true, message: '请输入客户名称!' }],
        contact: [{ required: true, message: '请输入联系人!' }],
        telephone: [{ required: true, message: '请输入联系电话!' }],
        address: [{ required: true, message: '请输入地址!' }]
        // email: [
        //   { required: false },
        //   { pattern: /^([\w]+\.*)([\w]+)@[\w]+\.\w{3}(\.\w{2}|)$/, message: '请输入正确的电子邮件!' },
        // ],
      },
      url: {
        add: '/base/erpCustomer/add',
        edit: '/base/erpCustomer/edit',
        queryById: '/base/erpCustomer/queryById',
        getOneByCountryId: '/bussiness/simpleQuery/getOneByCountryId',
        tslSellProductsDetail: {
          list: '/base/erpCustomer/queryCustomerProductsDetailByMainId'
        }
      }
    }
  },
  computed: {
    formDisabled() {
      return this.disabled
    },
    updatedColumns() {
      // 如果需要动态调整列配置，可以通过 computed 返回
      return this.tslSellProductsDetailTable.columns
    }
  },
  created() {
    //备份model原始值
    this.modelDefault = JSON.parse(JSON.stringify(this.model))
  },
  mounted() {
    getAction("/base/erpCustomer/getSalesMan",{}).then((res) => {
      if(res.success){
        this.$nextTick(()=>{
          this.model.salesman=res.result.id
          this.model.salesmanName=res.result.realname
          console.log("2313212312")
          console.log("222",this.model.salesman,this.model.salesmanName)
        })
      }
    })
  },
  methods: {
    handleHr(row){
      console.log("hahahah",row)
      this.model.salesman=row.id
      this.model.salesmanName=row.employeeName
      console.log("结果",this.model.salesman,this.model.salesmanName)
    },
    handleClick(){
      this.$nextTick(()=>{
        this.$refs.hr.add()
      })
    },
    handleDeleteRow(row) {
      getRefPromise(this, this.refKeys[0]).then(vxeTable => {
        vxeTable.removeRowsById(row.rowId)

        // 强制响应式更新
        this.model.tslSellProductsDetail = vxeTable.getTableData()
        this.tslSellProductsDetailTable.dataSource = [...vxeTable.getTableData()]

        this.$message.success('删除成功')
      });
    },
    sellProductsOk(rows) {
      if (rows && rows.length > 0) {
        rows.forEach((item) => {
          let detail = {
            code: item.code,
            name: item.name,
            noneSpec: item.noneSpec,
            meUnit: item.meUnit,
            auUnit: item.auUnit,
            coRate: item.coRate
          }
          this.tslSellProductsDetailTable.dataSource.push(detail)
        })
      }
    },
    addProducts() {
      this.$nextTick(() => {
        this.$refs.selectModal.add()
      })
    },
    handleChangeTabs(key) {
      getRefPromise(this, key).then(vxeTable => {
        vxeTable.resetScrollTop()
      })
    },
    getCode() {
      let autoCodeUrl = '/sys/fillRule/executeRuleByCode/customer_code'

      postAction(autoCodeUrl, {}).then((res) => {
        this.model.code = res.result
        this.$forceUpdate()
      })
    },
    //国家下拉框切换后针对大洲进行赋值
    handleChange(value) {
      getAction(this.url.getOneByCountryId, { country: value }).then((res) => {
        this.model.continent = res.result.stateName
        this.$forceUpdate()
      })
    },
    add() {
      this.edit(this.modelDefault)
    },
    edit(record) {
      this.model = {
        ...this.modelDefault, // 保留初始值
        ...record // 覆盖为后端数据
      }
      this.editAfter()
    },
    requestSubTableData(url, params, table) {
      getAction(url, params).then(res => {
        if (res.success) {
          table.dataSource = res.result
          this.model.tslSellProductsDetail = res.result // 同步到 model
        }
      })
    },
    /** 调用完edit()方法之后会自动调用此方法 */
    editAfter() {
      this.$nextTick(() => {
      })
      // 加载子表数据
      if (this.model.id) {
        let params = { id: this.model.id }
        this.requestSubTableData(this.url.tslSellProductsDetail.list, params, this.tslSellProductsDetailTable)
      }
    },
    submitForm() {
      const that = this
      // 触发表单验证
      this.$refs.form.validate((valid) => {
        if (valid) {
          that.confirmLoading = true
          let httpurl = ''
          let method = ''
          if (!this.model.id) {
            httpurl += this.url.add
            method = 'post'
          } else {
            httpurl += this.url.edit
            method = 'put'
          }
          getRefPromise(this, this.refKeys[0]).then(vxeTable => {
            this.model.tslSellProductsDetail = vxeTable.getTableData()
          })
          httpAction(httpurl, this.model, method)
            .then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.$emit('ok')
              } else {
                that.$message.warning(res.message)
              }
            })
            .finally(() => {
              that.confirmLoading = false
            })
        }
      })
    }
  }
}
</script>